﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using data.jianvgroup.com;
using Microsoft.AspNetCore.Identity;
using data.jianvgroup.com.Entity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using jianvgroup.com.Common;
using Microsoft.Extensions.Logging;
using jianvgroup.com.Models.AccountViewModels;
using jianvgroup.com.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace jianvgroup.com.Controllers
{

    public class MangerUserController : Controller
    {

        private readonly JvgroupContext _db;
        private readonly UserManager<jvuser> _userManager;
        private readonly SignInManager<jvuser> _signInManager;
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly ILogger<MangerUserController> _log;
        public MangerUserController(JvgroupContext db,
            UserManager<jvuser> userManager,
            SignInManager<jvuser> signInManager,
            RoleManager<IdentityRole> roleManager,
            ILogger<MangerUserController> log)
        {
            _db = db;
            _userManager = userManager;
            _signInManager = signInManager;
            _roleManager = roleManager;
            _log = log;
        }

        // GET: /<controller>/
        public async Task<IActionResult> Index()
        {
            var msgerUserList = new List<MangerUserViewModel>();
            var storeUser = await _userManager.GetUsersInRoleAsync(Constant.MANGERROLE);
            var user = await _userManager.GetUsersInRoleAsync(Constant.SYSTEMROLE);
            if ((storeUser != null && storeUser.Any()))
            {
                foreach (var store in storeUser)
                {
                    user.Add(store);
                }
            }

            if (user != null && user.Count > 0)
            {
                var basePage = new BasePageModel() { SearchKeyWord = string.Empty, CurrentIndex = 1, TotalCount = user.Count };
                var userList = user.Skip((basePage.CurrentIndex - 1) * basePage.PageSize).Take(basePage.PageSize).OrderByDescending(x => x.Id).ToList();
                ViewData["pageModel"] = basePage;

                foreach (var item in userList)
                {
                    var roles = _userManager.GetRolesAsync(item).Result;
                    msgerUserList.Add(new MangerUserViewModel
                    {
                        UserName = item.UserName,
                        UserId = item.Id,
                        RoleName = (roles != null && roles.Any()) ? roles[0] : string.Empty
                    });
                }
            }

            return View(msgerUserList);
        }

        [HttpGet]
        // GET: /<controller>/
        public async Task<IActionResult> Create(MangerUserViewModel model, string id = null)
        {
            string roleName = string.Empty;
            if (!string.IsNullOrWhiteSpace(id))
            {
                var user = await _userManager.FindByIdAsync(id);
                if (user != null)
                {
                    var roles = _userManager.GetRolesAsync(user).Result;
                    roleName = (roles != null && roles.Any()) ? roles[0] : string.Empty;
                    model.UserId = user.Id;
                    model.UserName = user.UserName;
                }
            }
            ViewBag.Role = GetRoles(roleName);

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Save(MangerUserViewModel model)
        {
            bool isSuccessful = false;
            var jvUser = new jvuser
            {
                UserName = model.UserName,
                PasswordHash = model.Password,
                Email = model.UserName
            };
            if (string.IsNullOrWhiteSpace(model.UserId))
            {
                ///新增系统用户
                isSuccessful = await EditIndityRoleAsync(jvUser, model.Password, model.RoleName);
            }
            else
            {
                //编辑系统用户
                var user = await _userManager.FindByIdAsync(model.UserId);
                user.UserName = model.UserName;
                user.PasswordHash = model.Password;
                isSuccessful = await EditIndityRoleAsync(user);
            }
            if (isSuccessful)
            {

                return RedirectToAction(nameof(MangerUserController.Index), "MangerUser");
            }

            return RedirectToAction(nameof(MangerUserController.Error), "MangerUser", new { errorMsg = 500 });
        }

        public IActionResult Error(int errormsg)
        {
            string error = string.Empty;
            switch (errormsg)
            {
                case 500:
                    error = Constant.ERROECODE_500; break;
                case 100:
                    error = Constant.EEEROECODE_100; break;
                case 200:
                    error = Constant.ERROECODE_200; break;
                default:
                    return RedirectToAction(nameof(HomeController.Index), "Home");
            }

            ViewBag.Error = error;

            return View();
        }
        public async Task<IActionResult> Delete(string id = null)
        {
            int errorMsg = 0;
            var getUser = await _userManager.FindByIdAsync(id);
            if (getUser != null)
            {
                var deleted = await _userManager.RemoveFromRoleAsync(getUser, Constant.SYSTEMROLE);
                var user = await _userManager.DeleteAsync(getUser);
                if (user.Succeeded)
                {
                    return RedirectToAction(nameof(MangerUserController.Index), "MangerUser");
                }
                else
                {
                    errorMsg = 100;
                }
            }
            else
            {
                errorMsg = 200;
            }

            return RedirectToAction(nameof(MangerUserController.Error), "MangerUser", new { errorMsg = errorMsg });

        }

        private async Task<bool> EditIndityRoleAsync(jvuser user, string password, string roleName)
        {
            var isSuccess = false;
            try
            {
                var result = await _userManager.CreateAsync(user, password);
                var identityRole = new IdentityRole
                {
                    Name = roleName,
                };
                var identityRoleResult = new IdentityResult();
                if (!await _roleManager.RoleExistsAsync(roleName))
                {
                    identityRoleResult = await _roleManager.CreateAsync(identityRole);
                }
                var add = await _userManager.AddToRoleAsync(user, roleName);
                if (add.Succeeded)
                {
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                _log.LogError("编辑用户", "编辑用户异常，异常信息:" + ex.ToString());
            }

            return isSuccess;
        }

        private async Task<bool> EditIndityRoleAsync(jvuser user)
        {
            var isSuccess = false;
            try
            {
                var result = await _userManager.UpdateAsync(user);
                var token = await _userManager.GeneratePasswordResetTokenAsync(user);
                var identityResult = await _userManager.ResetPasswordAsync(user, token, user.PasswordHash);
                if (result.Succeeded && identityResult != null && identityResult.Succeeded)
                {
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                _log.LogError("编辑管理员异常" + ex.ToString());
            }

            return isSuccess;
        }

        private IList<SelectListItem> GetRoles(string id)
        {
            IList<SelectListItem> lstItem = new List<SelectListItem>();
            lstItem.Add(new SelectListItem()
            {
                Text = Constant.SYSTEMROLE,
                Value = Constant.SYSTEMROLE,
                Selected = Constant.SYSTEMROLE.Equals(id)
            });
            lstItem.Add(new SelectListItem()
            {
                Text = Constant.MANGERROLE,
                Value = Constant.MANGERROLE,
                Selected = Constant.MANGERROLE.Equals(id)
            });
           
            return lstItem;
        }
    }
}
